import axios, { AxiosRequestConfig } from 'axios';

// @ts-ignore
export function objectToParams<T>(params: T): string {
    return Object.keys(params)
        // @ts-ignore
        .map((key: keyof T) => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`).join('&');
}

export function uploadFile(
    url: string,
    files: {[fileId: string]: File},
    config: AxiosRequestConfig,
): any {
    const formData = new FormData();
    Object.entries(files).forEach(([fileId, file]) => {
        const hasFile = !!file;
        if (hasFile) formData.append(fileId, file);
    });

    return axios({
        method: 'POST', url, data: formData, headers: config.headers,
    });
}

export async function downloadFile(
    url: string,
    config: AxiosRequestConfig,
    fileName = 'file.pdf',
): Promise<any> {
    const response = await axios({
        url,
        method: 'GET',
        responseType: 'blob',
        headers: {
            ...config.headers,
        },
    });

    const outputUrl = window.URL.createObjectURL(new Blob([response as unknown as string], { type: 'application/pdf' }));
    const link = document.createElement('a');
    link.href = outputUrl;
    link.download = fileName;
    link.click();
}
